package com.xiaomaoaixue.wecom.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import com.xiaomaoaixue.constant.WeConstans;
import com.xiaomaoaixue.system.api.RemoteUserService;
import com.xiaomaoaixue.system.api.domain.SysUser;
import com.xiaomaoaixue.postapi.api.domain.WeUserInfoVo;
import com.xiaomaoaixue.wecom.annotation.SynchRecord;
import com.xiaomaoaixue.wecom.client.WeUserClient;
import com.xiaomaoaixue.wecom.config.RuoYiConfig;
import com.xiaomaoaixue.wecom.constants.SynchRecordConstants;
import com.xiaomaoaixue.wecom.domain.dto.WeUserInfoDto;
import com.xiaomaoaixue.wecom.service.IWeUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 通讯录相关客户Service业务层处理
 *
 * @author ruoyi
 * @date 2020-08-31
 */
@Service
public class WeUserServiceImpl implements IWeUserService {

    @Autowired
    private WeUserClient weUserClient;


    @Autowired
    private RuoYiConfig ruoYiConfig;

    @Autowired
    private RemoteUserService remoteUserService;


    /**
     * 同步成员
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SynchRecord(synchType = SynchRecordConstants.SYNCH_MAIL_LIST)
    public void synchWeUser() {
        //同步部门
        //SpringUtils.getBean(IWeDepartmentService.class).synchWeDepartment();
        //获取通讯录所有成员列表
        List<SysUser> weUsers = weUserClient.list(WeConstans.WE_ROOT_DEPARMENT_ID,
                WeConstans.DEPARTMENT_SUB_WEUSER).getSysUsers();
        if (CollectionUtil.isNotEmpty(weUsers)) {
            //不存在的客户设置为离职未分配状态 （省略，需求还不明确）


            // 一批500个保存
            List<List<SysUser>> lists = Lists.partition(weUsers, 500);
            for (List<SysUser> list : lists) {
                remoteUserService.syncWeUser(list);
            }

        }


    }

    @Override
    public WeUserInfoVo getUserInfo(String code) {
        WeUserInfoDto userInfo = weUserClient.getUserInfo(code);

        return new WeUserInfoVo.Builder()
                .userId(userInfo.getUserId())
                .deviceId(userInfo.getDeviceId())
                .externalUserId(userInfo.getExternal_userid())
                .openId(userInfo.getOpenId())
                .build();
    }


}
